package fr.utbm.lo53;

import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class UDPHandler extends Thread   {
	private DatagramSocket SocketUDP = null ;
	public UDPHandler(DatagramSocket SocketUDP) {
		this.SocketUDP = SocketUDP;
	}
	public void run() {
		if (SocketUDP != null) {
			System.out.println("handler start");
			backGround();
		}
    }
	public void traitementReceive(String receive) {
		String [] splitReceive = receive.split(";");
		System.out.println(splitReceive[0]);
		if (splitReceive[0].equals("RSSI")) {
			System.out.println("stock");
			offlinePhase(splitReceive);
		}
	}
	public void offlinePhase(String [] splitReceive) {
		Connection connec = ConnectionBD.getInstance().connection;
		String macaddr = splitReceive[5];
		double X = Double.parseDouble(splitReceive[1]);
		double Y = Double.parseDouble(splitReceive[2]);
		double val = Double.parseDouble(splitReceive[6]);
		int idMAPS = 1;
		int idAP = ConnectionBD.getInstance().getIdApByMac(macaddr);
		int idLoc = ConnectionBD.getInstance().getIdLocByXY(X,Y,idMAPS);
		ConnectionBD.getInstance().insertRSSI(idAP,idLoc,val);
		System.out.println("idAP = " + idAP);
		System.out.println("idLOC = " + idLoc);
		System.out.println(connec);
	}
	public void backGround() {
		byte[] buffer = new byte[1024];
		DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
		//while (true) {
			 //try {
				//SocketUDP.receive(packet);
				System.out.println("receive packet");
				ByteArrayInputStream stream = new ByteArrayInputStream(buffer);
                DataInputStream data = new DataInputStream(stream);
               // String receive = data.readUTF();
                String receive = "RSSI;1;1;mid;ZZ:ZZ:ZZ:ZZ:ZZ:ZZ;AP:AP:AP:AP:AP:AP;-30.5";
                traitementReceive(receive);

			/*} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}*/
		//}
	}

}
